package com.startx.core.netty.pipeline;

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import com.startx.core.config.holder.ConfigHolder;
import com.startx.core.netty.handler.HttpHandler;
import com.startx.core.system.model.StartxConfig;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;

public class HttpPipeline  extends ChannelInitializer<SocketChannel> {

	@Override
	public void initChannel(SocketChannel ch) throws Exception {

		ChannelPipeline pipeline = ch.pipeline();
		
		StartxConfig config = ConfigHolder.getConfig();
		if(config.isSSL()) {
			KeyStore ks = KeyStore.getInstance("JKS");
			InputStream ksInputStream = HttpPipeline.class.getResourceAsStream(config.getJksPath());
			ks.load(ksInputStream, config.getJksPwd().toCharArray());
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks,config.getJksPwd().toCharArray());
			SSLContext sslCtx = SSLContext.getInstance("TLS");
			sslCtx.init(kmf.getKeyManagers(), null, null);
			
			SSLEngine engine = sslCtx.createSSLEngine();
    		engine.setUseClientMode(false);
    		engine.setNeedClientAuth(false);
    		pipeline.addLast("ssl",new SslHandler(engine));
		}
		
		pipeline.addLast(new HttpRequestDecoder());
		pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
		pipeline.addLast(new HttpHandler());
		pipeline.addLast(new HttpResponseEncoder());
	}

}
